package cn.gong.jizhang.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;

import cn.gong.jizhang.manager.ActivityManager;
import cn.gong.jizhang.manager.NetStateManager;
import cn.gong.jizhang.manager.TaskManager;
import cn.gong.jizhang.manager.NetStateManager.NetState;
import cn.gong.jizhang.utils.DebugUtils;


public class MainService extends Service implements Runnable {
	private byte[] lock = new byte[0];
	private boolean isrun;
	private TaskManager taskManager;
	// private ActivityManager activityManager;
	public static boolean serviceState = false;

	public BroadcastReceiver netStateReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			NetStateManager.setmContext(context);
			NetworkInfo info = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
			if (info != null && info.isAvailable()) {
				switch (info.getType()) {
				case ConnectivityManager.TYPE_WIFI:
					NetStateManager.CUR_NETSTATE = NetState.WIFI;
					break;
				case ConnectivityManager.TYPE_MOBILE:
					NetStateManager.CUR_NETSTATE = NetState.Mobile;
					break;
				}
			} else {
				NetStateManager.CUR_NETSTATE = NetState.NOWAY;
			}
		}
	};

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();

		DebugUtils.debug("service onCreate", getClass());

		IntentFilter mFilter = new IntentFilter();
		mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		registerReceiver(netStateReceiver, mFilter);

		taskManager = TaskManager.getInstance();
		// activityManager = ActivityManager.getInstance();

		isrun = true;
		serviceState = true;

		Thread t = new Thread(this);
		t.start();
	}

	@Override
	public void run() {
		while (isrun) {
			synchronized (lock) {
				if (taskManager.getSize() > 0) {
					doTask(taskManager.getTask(0));
				} else {
					try {
						Thread.sleep(1000);
					} catch (Exception e) {
					}
				}
			}
		}
	}

	private void doTask(BackstageTask task) {
		task.doTask();
		taskManager.removeTask(task);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		DebugUtils.debug("service onDestroy", getClass());

		isrun = false;
		serviceState = false;
		unregisterReceiver(netStateReceiver);
	}
}
